module CodeGraphs
  
  class DirectoryPicker < Widget
    
    class Item < Element
      def render
        self.file = nil
        super()
      end
    end
    
    attr_accessor :folder_blacklist
    
    def initialize root = nil
      super()
      @root = root || File.dirname(__FILE__)+'/..'
      @items = nil
      @folder_blacklist = MatchList.new      
    end
    
    def items
      if !@items
        @items = []
        @tree_root = tree(@root)
        @tree_root.className = 'filetree'
      end
      @items
    end
    
    def render
      items
      #tree_root.children.each { |li| li.className = 'closed' }
      context.page.link_js file_url('jquery-1.2.6.js')
      context.page.link_js file_url('jquery.treeview.js')
      context.page.link_css file_url('jquery.treeview.css')
      context.page.head.e :script, "jQuery(function($) { $(\"##{@tree_root.id}\").treeview(); })"
      super()
    end
    
    def tree root, dir = ''
      e :ul do
        Dir.foreach(File.join(root, dir)) do |filename|          
          next if filename[0,1] == '.'
          file = File.join(root, dir, filename)
          if File.directory?(file) && !@folder_blacklist.matches(file)
            e :li, :class => 'closed' do
              @items << add(Item.new(:span, :class => 'folder', :innerHTML => filename, :file => File.join(dir, filename)))
              child_tree = tree root, File.join(dir, filename)
              if child_tree.children.length == 0
                # no empty uls..
                child_tree.tagName = nil
              end
            end
          end
        end
      end
    end
    
  end

end